package com.wjh.yygh.msm.controller;

import com.wjh.yygh.common.result.Result;
import com.wjh.yygh.msm.service.MsmService;
import com.wjh.yygh.msm.utils.RandomUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Api(tags = "短信平台")
public class MsmApiController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送验证码")
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone) {
//        从Redis获取验证码获取 ,ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok(code);
        } else {
//        如果获取不到 ，生成验证码，整合服务器发送，设置过期时间
            code = RandomUtils.getSixBitRandom();
            boolean isSend =  msmService.send(phone,code); //发送验证码
            if (isSend) {
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES); //5分钟
                return Result.ok();
            }else {
                return Result.fail().message("发送短信失败");
            }

        }

    }

}
